package com.lovo.bbs.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.lovo.bbs.bo.ForumBo;
import com.lovo.bbs.bo.ForumStatBo;
import com.lovo.bbs.bo.TopicBo;
import com.lovo.bbs.vo.ForumStatVo;
import com.lovo.bbs.vo.ForumVo;
import com.lovo.bbs.vo.TopicVo;

/**
 * 打开单个论坛时,初始化该论坛相关数据
 * @author tiancen2001
 *
 */
public class InitForumFilter implements Filter{

	public void destroy() {	
	}

	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		
		//论坛ID
		int forumid =  Integer.parseInt(req.getParameter("fid"));
		
		//取得置顶主题列表
		TopicBo topicBo = new TopicBo();
		ArrayList<TopicVo> topList = topicBo.getTopTopics(forumid);
		req.setAttribute("topList", topList);
		
		//请求页码 
		String queryPage =  request.getParameter("page");
		if(queryPage==null){
			queryPage="1";
		}
		req.setAttribute("queryPage", Integer.valueOf(queryPage));
		
		//取得该页的主题列表(数据库分页,根据请求的页码分页)
		ArrayList<TopicVo> topicList = topicBo.getTopics(forumid,Integer.parseInt(queryPage));
		req.setAttribute("topicList", topicList);
		
		//取得forumMap
		ServletContext context=req.getSession().getServletContext();
		HashMap<Integer,ForumVo> forumMap = (HashMap<Integer,ForumVo>)context.getAttribute("forumMap");
		//更新forumMap和论坛列表
		ForumBo boardBo = new ForumBo();
		if(forumMap==null){
			// 取得所有论坛列表
			ArrayList<ForumVo> forumList =  boardBo.getAllForum();
			//更新论坛列表 
			context.setAttribute("forumList", forumList);
			// 更新forumMap
			context.setAttribute("forumMap", boardBo.getForumMap(forumList));
		}
		req.setAttribute("forumMap", forumMap);//forumMap
		
		//取得总主题数
		int topicNum =forumMap.get(forumid).getTopicNum();
		req.setAttribute("topicNum", Integer.valueOf(topicNum));
		
		// 取得网站杂项信息
		ForumStatVo forumInfo = (ForumStatVo)context.getAttribute("forumInfo");
		//更新网站杂项信息
		if(forumInfo==null){
			forumInfo = new ForumStatBo().getForumInfo();
		}
		context.setAttribute("forumInfo", forumInfo);
		req.setAttribute("forumInfo", forumInfo);
		
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	}

}
